package com.foocus.foocuscloud.common.interceptor;

import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.sql.Statement;
import java.util.Properties;


@Intercepts({
        @Signature(
                type = StatementHandler.class,
                method = "query",
                args = {
                        Statement.class,
                        ResultHandler.class
                }
        ),
        @Signature(
                type = StatementHandler.class,
                method = "update",
                args = {
                        Statement.class
                }
        )
})
@Component
public class SqlLogInterceptor implements Interceptor {
    private static final Logger LOGGER = LoggerFactory.getLogger(SqlLogInterceptor.class);
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        long startTime = System.currentTimeMillis();
        StatementHandler target = (StatementHandler)invocation.getTarget();
        String sql = target.getBoundSql().getSql();
        ParameterHandler parameterHandler = target.getParameterHandler();
        Object parameters = parameterHandler.getParameterObject();

        Object proceed = invocation.proceed();
        long totalTime = System.currentTimeMillis() - startTime;
        LOGGER.info("Print SQL >>>> \n SQL语句：{}\n 参数：{}\n 耗时：{}ms", sql, parameters, totalTime);
        return proceed;
    }

    @Override
    public Object plugin(Object target) {

        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
